<?php

namespace backend\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "{{%admin_role}}".
 *
 * @property int $id
 * @property int $pid 父级id
 * @property string $name 名称
 * @property string $remark 备注
 * @property int $status 状态
 * @property int $isdelete
 * @property int $create_at
 * @property int $update_at
 */
class AdminRole extends ActiveRecord
{

    /**
     * @return array|array[]
     */
    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className()
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%admin_role}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['pid', 'status', 'isdelete', 'created_at', 'updated_at'], 'integer'],
            [['name'], 'string', 'max' => 20],
            [['remark'], 'string', 'max' => 255],
            [['rule'], 'string', 'max' => 512],

        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'pid' => 'Pid',
            'name' => 'Name',
            'remark' => 'Remark',
            'status' => 'Status',
            'isdelete' => 'Isdelete',
            'created_at' => 'Create At',
            'updated_at' => 'Update At',
        ];
    }

    /**
     * @return array|ActiveRecord[]
     */
    public function getRoles()
    {
        return self::find()
            ->select(['id', 'name'])
            ->where(['status' => 1, 'isdelete' => 0])
            ->orderBy('id ASC')
            ->asArray()->all();
    }

    /**
     * @param $rule
     */
    public function setRule($rule)
    {
        $rules = [];
        $rule = explode(',', $rule);
        foreach ($rule as $val) {
            $pids = AdminRule::instance()->getAllPid($val);
            $rules = array_merge($rules, $pids);
        }
        $rule = array_unique(array_merge($rule, $rules));
        $this->rule = implode(',', $rule);

    }
}
